package com.taotao.interceptor.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;

/**
 * 拦截Sql语法和会话构建的处理
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare",
        args = {Connection.class, Integer.class}),
})
@Component
@Slf4j
public class MybatisSqlInterceptor implements Interceptor {
    @Value("${mayikt.pagehelper.rule}")
    private String pagehelperRule;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        log.info("<mayikt limit>");
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
        //sql类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        switch (sqlCommandType) {
            // 判断sql语句是为查询类型
            case SELECT:
                extendLimit(statementHandler);
                break;
        }


        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }


    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 对sql实现 修改  加上limit
     */
    private void extendLimit(StatementHandler statementHandler) throws NoSuchFieldException, IllegalAccessException {
        // 获取到原生sql语句
        BoundSql boundSql = statementHandler.getBoundSql();
        Class<? extends BoundSql> aClass = boundSql.getClass();
        // 使用反射机制修改原生sqk语句
        Field sql = aClass.getDeclaredField("sql");
        sql.setAccessible(true);
        String oldSqlStr = boundSql.getSql();
        // 后面加上 limit
        sql.set(boundSql, oldSqlStr + "   " + pagehelperRule);
    }


}